<?php
namespace framework;

class Server {
	private $http;
	private $route;
	public static $_instance;

	public function __construct($ip,$port) {
		$this->ip = $ip;
		$this->container = new Container();
		$this->port = $port;
		$this->base = new \EventBase();
		$this->http = new \EventHttp($this->base);
		self::$_instance = $this;
	}


	public function init() {

	}

	public function run() {
		$res = $this->http->bind($this->ip,$this->port);
		if(!$res) {
			echo "bind error!\n";
		}
		$this->http->setDefaultCallback(array($this,'handler'));
        $this->http->setCallback('/',array($this,'handler'));
		$this->base ->loop();
		return ;
	}

	public function handler($req,$data) {
	    $uri = $req->getUri();
        $buf = $req->getOutputBuffer();
        $uri =parse_url($uri);
        $path = $uri['path'];
       	$params = array();
       	if(!empty($uri['query'])) {
       		parse_str($uri['query'],$params);
       	}
 		
        if(!array_key_exists($path,$this->route)) {
            $buf->add(json_encode("not found!"));
            $req->sendReply(200, "OK");
            return ;
        }

        $ctrl =  new $this->route[$path][0];
        $ctrl->req = $req;
        call_user_func_array(array($ctrl,$this->route[$path][1]),array('req'=>$req));
        return ;
    }

	public function route($path,$func) {
	    $this->route[$path] = $func;
	}

	
}